import axios from "axios";
import {
  ElMessage
} from "element-plus";
import store from "../store";
import router from "@/router";
import {
  CookieUtil,
  TokenKey,
  refreshTokenUtil
} from "@/utils/cookie-util";

// 是否正在刷新的标记
let isRefreshing = false;
// 重试队列，每一项将是一个待执行的函数形式
let requests = [];

// axios.defaults.withCredentials = true;

const baseURLConfig = {
  defaultUrl: process.env.VUE_APP_BASE_API || "",
  otherUrl: process.env.VUE_APP_GET_NOTICE || ''
}

// debugger
// const service = function baseRequest(options) {
//   console.log(options)
//   switch (options.urlType) {
//     case 'oa':
//       return axios.create({
//         baseURL: baseURLConfig.otherUrl,
//         timeout: 15000
//       })
//     default:
//       return axios.create({
//         baseURL: baseURLConfig.defaultUrl,
//         timeout: 15000
//       })
//   }
// }

// // 创建axios实例
const service = axios.create({
  baseURL: baseURLConfig.defaultUrl || "",
  timeout: 15000 // 请求超时时间
});

const service2 = axios.create({
  baseURL: baseURLConfig.otherUrl || "",
  timeout: 15000 // 请求超时时间
});

service.setToken = token => {
  service.defaults.headers.Authorization = token;
  CookieUtil.set(TokenKey, token); // jwt
};

service2.setToken = token => {
  service2.defaults.headers.Authorization = token;
  CookieUtil.set(TokenKey, token); // jwt
};
/**
 * 通用请求拦截配置
 * @param {*} config
 */
const instanceConf = config => {
  config.headers.platform = `PC`;
  if (store.getters.token) {
    config.headers.Authorization = CookieUtil.get(TokenKey); // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config;
};
// request拦截器
service.interceptors.request.use(instanceConf, error => {
  // console.log(error); // for debug
  Promise.reject(error);
});

// request拦截器
service2.interceptors.request.use(instanceConf, error => {
  // console.log(error); // for debug
  Promise.reject(error);
});

// http response 拦截器
service.interceptors.response.use(
  async response => {
      let data = {};
      if (response || response.data) {
        const code = Number(response.status);
        if (code === 200) {
          const errorCode = response.data.ErrorCode || response.status;
          if (errorCode === 0 || errorCode === 200) {
            data = response.data;
          } else if (errorCode === 3107) {
            if (!isRefreshing) {
              try {
                const token = await refreshTokenUtil(axios);
                isRefreshing = true;
                if (token) {
                  service.setToken(token);
                  response.config.headers.Authorization = token;
                  // 已经刷新了token，将所有队列中的请求进行重试
                  requests.forEach(cb => cb(token));
                  requests = [];
                  let params = response.config.data;
                  if (params) {
                    params = JSON.parse(response.config.data || "{}");
                    params.accessToken = token;
                    response.config.data = JSON.stringify(params);
                  }
                  return service(instanceConf(response.config));
                }
              } catch (error) {
                // 刷新时候直接判断token 不用判断code
                console.error("refreshtoken error =>", error);
                routerRedirect({
                  redirect: router.currentRoute.fullPath
                });
              } finally {
                isRefreshing = false;
              }
            } else {
              // 正在刷新token，将返回一个未执行resolve的promise
              return new Promise(resolve => {
                // 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
                requests.push(token => {
                  response.config.headers.Authorization = token;
                  resolve(service(instanceConf(response.config)));
                });
              });
            }
          } else {
            let error;
            if (response.data) {
              error = response.data.ErrorMessage;
            }
            ElMessage.error(error || "网络请求错误！");
          }
        }
      }
      return data;
    },
    error => {
      // console.log(error);
      if (error && error.response) {
        const {
          status,
          data = {}
        } = error.response;
        const msg = data.msg;
        if (status === 401) {
          routerRedirect({
            redirect: router.currentRoute.fullPath
          });
        } else if (status === 403) {
          ElMessage({
            type: "warning",
            message: msg || "抱歉，您无权限访问该页面"
          });
        } else if (status === 404) {
          ElMessage({
            type: "error",
            message: "访问接口不存在"
          });
        } else if (status === 503) {
          ElMessage({
            type: "error",
            message: "应用未启动，请联系运维人员"
          });
        } else {
          ElMessage({
            type: "error",
            message: msg || `接口异常,请联系开发人员`
          });
        }
      } else if (
        error.code === "ECONNABORTED" &&
        error.message.indexOf("timeout") !== -1
      ) {
        ElMessage({
          type: "error",
          message: `请求超时，请重新尝试`
        });
      } else {
        ElMessage({
          type: "error",
          message: error || "请联系开发人员"
        });
      }
    }
);
/**
 * 重定向
 */
const routerRedirect = ({
  path = "/login",
  redirect
}) => {
  ElMessage.warning(`身份过期，请重新登录!`);
  if (router.currentRoute.path !== "/login") {
    setTimeout(() => {
      router.replace({
        path,
        query: {
          redirect
        }
      });
    }, 1200);
  }
};
export default {
  service,
  service2
};
